package cn.tm.liu.mvc.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Marvin.L
 * @description
 * @date 2022.03.30 11.24
 */
@Slf4j
@RestControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attr.getRequest();
        ResponseResult responseResult = (ResponseResult) request.getAttribute(ResponseResult.RESPONSE_RESULT_ANN);
        log.info("请求是否为ResponseResult:{}", null != responseResult);
        return responseResult == null == true ? false : true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<?
            extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (body instanceof HttpResult) return body;
        log.info("返回体重写:{}", body);
        return HttpResult.success(body).extra();
    }

    @ExceptionHandler(Exception.class)
    public HttpResult ClassCastException(HttpServletRequest request, Exception ex) {
        ex.printStackTrace();
        return HttpResult.failure(ex.getMessage()).extra();
    }

}